<template>
  <mu-h-box class="mu-absolute-fit" cellpadding>
    <mu-v-box size="30%" class="margin-r-8" bordered>
      <mu-h-box class="pad-8">
        <mu-button-editor
          icon="search"
          :value="searchKey"
          icon-align="left"
          placeholder="按名称搜索"
          size="auto"
          @change="onSearch"
        />
      </mu-h-box>
      <mu-flex-item id="function-grid" size="auto" bordered-top class="grid-container" />
    </mu-v-box>
    <mu-v-box size="70%" bordered>
      <div class="bar bg pad-8" style="font-weight: bold; font-size: 1.1rem">函数式：</div>
      <div cellspacing size="auto">
        <span v-html="example" />
      </div>
      <div class="bar bg pad-8" bordered-top style="font-weight: bold; font-size: 1.1rem">说明：</div>
      <div cellspacing size="auto">
        <span v-html="remark" />
      </div>
    </mu-v-box>
  </mu-h-box>
</template>

<script>
  import cloneDeep from 'lodash.clonedeep'
  import userTheme from '@utils/grid-theme'
  import kakaGrid from '@mctech/kaka-grid'
  import { functionLibrary } from '@mctech/biz-data-utils'
  import debounce from 'lodash.debounce'

  export default {
    data () {
      return {
        searchKey: '',
        activeFunc: {},
        dataSource: []
      }
    },
    computed: {

      searchedData () {
        const records = functionLibrary.filter((item) => item.name.toLowerCase().includes(this.searchKey.toLowerCase()))
        records.forEach((item, index) => {
          item.serialNo = index + 1
        })
        return records
      },

      example () {
        return Object(this.activeFunc).example || ''
      },

      remark () {
        return Object(this.activeFunc).remark || ''
      }

    },

    watch: {
      searchedData (val) {
        this.refresh(val)
      }
    },

    mounted () {
      this.$nextTick(() => {
        this.initGrid()
        this.refresh(cloneDeep(functionLibrary))
        this.grid.focusGridCell('name', 0)
      })
    },

    methods: {

      onSearch: debounce(function (val = '') {
        this.searchKey = val.trim()
      }, 500),

      refresh (data) {
        this.dataSource.splice(0, this.dataSource.length, ...cloneDeep(data))
        this.cachedDataSource.length = data.length
        this.treeDataSource.refresh()
        this.grid.invalidate()
      },

      initGrid () {
        if (this.grid) {
          return
        }
        const me = this

        const copyUserTheme = cloneDeep(userTheme)
        copyUserTheme.highlightBorderColor = 'transparent'
        copyUserTheme.frozenRowsBorderColor = (args) => {
          if (args.col === 0) {
            return [null, '#E8E8E8', '#E8E8E8', null]
          }
          return [null, null, '#E8E8E8', null]
        }
        copyUserTheme.borderColor = (args) => {
          if (args.col === 0) {
            return [null, '#E8E8E8', '#E8E8E8', null]
          }
          return [null, null, '#E8E8E8', null]
        }
        copyUserTheme.defaultRowHeight = 40

        this.grid = new kakaGrid.ListGrid({
          theme: copyUserTheme,
          parentElement: me.$el.querySelector('#function-grid'),
          singleSelection: true,
          hiddenHeader: false,
          header: [
            {
              field: 'serialNo',
              caption: '序号',
              width: 50,
              headerStyle: { textAlign: 'center' },
              style: (rec) => {
                return {
                  textAlign: 'center',
                  bgColor: Object(this.activeFunc).id === rec.id ? '#F4FBFF' : '#ffffffff'
                }
              }
            },
            {
              field: 'name',
              caption: '函数名称',
              headerStyle: { textAlign: 'center' },
              width: 'auto',
              minWidth: 80,
              style: (rec) => {
                return {
                  bgColor: Object(this.activeFunc).id === rec.id ? '#F4FBFF' : '#ffffffff'
                }
              },
              columnType: new kakaGrid.columns.type.Column({
                draw: (value, ctx, opt) => {
                  ctx.save()
                  try {
                    var x = opt.rect.left + opt.rect.width - 40
                    var y = opt.rect.top + (opt.rect.height - 12) / 2
                    ctx.fillStyle = '#333'
                    ctx.fillText(value, opt.rect.left + 8, y)
                    ctx.fillStyle = '#008cd6'
                    ctx.fillText('插入', x, y)
                  } finally {
                    ctx.restore()
                  }
                  return false
                }
              }),
              action: new kakaGrid.columns.action.InlineInputEditor({
                type: 'text',
                disableInput: true,
                disableAction: rec => rec.parentId === -1,
                action: rec => {
                  if (rec) {
                    this.$emit('selected', rec.formula)
                  }
                }
              })
            }
          ]
        })

        this.cachedDataSource = kakaGrid.data.CachedDataSource.ofArray(this.dataSource)
        this.treeDataSource = new kakaGrid.data.TreeDataSource(this.cachedDataSource, {
          keyField: 'id'
        })
        this.grid.dataSource = this.treeDataSource

        this.grid.addEventListener(kakaGrid.ListGrid.EVENT_TYPE.SELECTED_CELL, ({ row }, selected) => {
          if (selected && row > 0) {
            this.activeFunc = this.grid.getRowRecord(row)
          }
        })
      }
    }
  }
</script>
